package com.token;

import com.pojo.User;
import com.service.ShiroService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
@SuppressWarnings("all")
@Component
public class LoginRealm extends AuthorizingRealm {

    /**
     *  用户DAO查询用户角色
     *  角色权限表DAO查出对应权限
     */


    @Autowired
    private ShiroService shiroService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    /**
     * 管授权
     * @param principals
     * 通过二进制比对限制用户可以访问的url
     * @return
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String tokenString = principals.toString();
        String username = JwtUtil.getUsername(tokenString);
        User u = shiroService.freshToken(username,tokenString);
        Set<String> resources = shiroService.getUserResources(u);
        authorizationInfo.addStringPermissions(resources);
        return authorizationInfo;
    }

    /**
     * 管登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //取用户名，如果为null则无效
        String otoken = (String) token.getPrincipal();
        return new SimpleAuthenticationInfo(otoken, otoken, getName());

    }
}
